package trunk.hadoop;

// prevent heap bomb in case of hordes of offset results

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class outputStringWrapper {
    public static final int SIZE_LIMIT = 16 * 1024 * 1024;

    private StringBuilder output;
    private static int curChunkIndex = 0;
    private int start, end;
    private boolean sizeExceed = false;

    public outputStringWrapper(){
        output  = new StringBuilder();
        start   = curChunkIndex;
        end     = start;
    }

    public int getFChunkIndex() {return start;}
    public int getLChunkIndex() {return end;}
    public boolean isExceed()   {return sizeExceed;}
    public String getValue()    {return output.toString();}

    public StringBuilder appendOffset(int valueIn){
        appendOffset(String.valueOf(valueIn));
        return output;
    }

    public StringBuilder appendOffset(String valueIn){
        PrintWriter print = null;

        if (!valueIn.equals("-1")) {
            if (valueIn.length() + output.length() < SIZE_LIMIT)     // combine and still less than limit
            {
                /*
                if (output.length() == 0)    // empty stringbuilder
                    output.append(valueIn);
                else*/
                output.append(',').append(valueIn);
            } else {
                try {
                    sizeExceed = true;
                    // memory dump
                    print = new PrintWriter(new FileOutputStream(new File(String.valueOf(curChunkIndex))));
                    print.println(output.toString());
                    print.flush();

                    // set index
                    curChunkIndex++;
                    end++;

                    // make new stuff
                    output = new StringBuilder();
                    output.append(',').append(valueIn);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (print != null) print.close();
                }
            }
            return output;
        }
        else
            return null;
    }
}
